package com.xxxx.server.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxxx.server.mapper.MenuRoleMapper;
import com.xxxx.server.mapper.RoleMapper;
import com.xxxx.server.pojo.RespBean;
import com.xxxx.server.pojo.Role;
import com.xxxx.server.service.IRoleService;
import com.xxxx.server.utils.AssertUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhoubin
 * @since 2020-10-15
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

	@Autowired
	private RoleMapper roleMapper;
	@Resource
	private MenuRoleMapper menuRoleMapper;

	/**
	 * 根据用户id查询角色
	 *
	 * @return
	 */
	@Override
	public List<Role> getRolesByAdminId(Integer adminId) {
		return roleMapper.getRolesByAdminId(adminId);
	}

	/**
	 * 查询所有角色
	 *
	 * @return
	 */
	@Override
	public List<Role> getRolesAll() {
		return roleMapper.selectRolesAll();
	}

	/**
	 * 添加角色
	 * @param role
	 * @return
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public RespBean addRole(Role role) {
		//角色不能为空
		AssertUtil.isTrue(null==role,"角色不能为空");
		//name不为空
		AssertUtil.isTrue(null==role.getName()||"".equals(role.getName()),"角色英文名不能为空");
		//角色中文名不能为空
		AssertUtil.isTrue(null==role.getNameZh()||"".equals(role.getNameZh()),"角色中文名不能为空");

		//添加角色
		Integer sum = roleMapper.insertRole(role.getName(),role.getNameZh());
		AssertUtil.isTrue(sum!=1,"角色添加失败");
		return RespBean.success("角色添加成功");
	}

	/**
	 * 根据roleId删除角色
	 * @param rid
	 * @return
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public RespBean deleteByRoleId(Integer rid) {
		AssertUtil.isTrue(null==rid,"角色id不能为空");
		AssertUtil.isTrue(null==roleMapper.selectById(rid),"该角色不存在");
		//获得该角色下权限条数
		Integer count = menuRoleMapper.getCountByRoleId(rid);
		//清空该角色下所有访问资源
		Integer sum = menuRoleMapper.deleteByRoleId(rid);
		AssertUtil.isTrue(count!=sum,"角色删除失败");

		//删除该角色
		Integer id = roleMapper.deleteById(rid);
		AssertUtil.isTrue(null==id,"角色删除失败");
		return RespBean.success("角色删除成功");
	}
}

